<?php
namespace app\index\Controller;

use app\common\controller\Base;
//use think\facade\Request;
use think\Request;
use think\captcha\Captcha;
use think\facade\Session;
use think\facade\Cache;
use app\common\model\Article;
use app\common\model\Collection;
use think\Db;
use app\common\model\User as userModel;
use think\Upload;

class User extends Base
{
	//空操作
	public function _empty()
	{
		return $this->kong();
	}
	protected function kong()
	{
		return $this->error('非法操作，没有当前方法');
	}
	
	//用户中心
	public function index()
	{
		$this->isLogin();
		$user['user_id'] = session::get('user_id');
		$username = session::get('user_name');
		
        return view();
    }
	//文章管理
	public function post()
	{
		$this->isLogin();
		//发表的帖子
		$user['user_id'] = session::get('user_id');
		$username = session::get('user_name');
		$article = Article::withCount('comments')->where('user_id',$user['user_id'])->order('update_time','desc')->paginate(10);
		$article->count();
		$this->assign('article',$article);
		//收藏的帖子
		$collect = Collection::with('article')->where('user_id',$user['user_id'])->order('create_time','desc')->paginate(10);
		$this->assign('collect',$collect);
		
        return $this->fetch();
    }
	
	//取消收藏
	public function delete()
	{
		$result = Collection::where('article_id',input('id'))->delete();
		if($result){
			$this->success('取消成功');
		} else {
			$this->error('取消失败');
		}
	}
	//基本设置
    public function set()
	{
		$this->isLogin();
		$user['user_id'] = session::get('user_id');
		$user = UserModel::find($user['user_id']);
		$this->assign('user',$user);
		 return $this->fetch();
	}
	
	
	//用户设置-我的资料
	public function setuser(Request $request)
	{
		$this->isLogin();
			$data = $request->post();
			$validate = new \app\common\validate\User();
			$result = $validate->scene('Set')->check($data);
			if(!$result){
				$this->error($validate->getError());
			}
			else {
				$result = model('User')->set($data);
				if($result==1){
					$this->success('资料更新成功','index/user/set');
				}else{
					$this->error($result);
				}
			}
    }

	//用户上传新头像
	public function uploadHeadImg()
    {
        $file = Request()->file('file');
		$info = $file->validate([
			'size' => 100000,
			'ext' => 'jpeg,jpg,png,gif'
		])->move('uploads/' );
        if($info){
            $name = $info->getFilename();
            $name_path =str_replace('\\',"/",$info->getSaveName());	
			$image = \think\Image::open("uploads/$name_path");
			$image->thumb(168, 168)->save("uploads/$name_path");

            //查出当前用户并把得到的用户头像名存入数据库
            $userId = Session::get('user_id');
            $result = Db::name('user')
                ->where('id',$userId)
                ->update(['user_img'=>$name_path]);
            //$user = userModel::where('id',$userId)->find();
            //$user->user_img = $name;
            //$result = $user->allowField(true)->save();

            if($result) {
                //成功上传后 获取上传信息
                $res['status'] = '0';
                $res['msg'] = "上传成功";
                $res["url"] = "/uploads/".$name_path;
                $res['title'] = $name;
            } else {
                $this->error('图片上传失败');
            }
        }else{
            // 上传失败获取错误信息
            $res['status'] = "2";
            $res['msg'] = "上传出错".$file->getError();
            $res['url'] ='';
        }
	return $res;
	}


    public function message()
    {
		$this->isLogin();
        return view();
    }

    public function home()
    {
		//$this->isLogin();
		$userID = input('id');
		//halt($userID);
		Session::get('user_id');
		//用户
		$u = Db::name('user')->field('name,nickname,city,sex,sign,user_img,point,create_time')->find($userID ?: Session::get('user_id'));
		//用户发贴
		$arts = Db::name('user')->alias('u')->join('article a','u.id = a.user_id')->field('u.id,a.id,a.title,a.pv,a.is_hot,a.create_time')->where('a.user_id',input('id') ?: Session::get('user_id'))->where(['status' => 1])->select();
		//用户回答
        $reys = Db::name('comment')->alias('c')->join('article a','c.article_id = a.id')->field('a.id,a.title,c.content,c.create_time')->where('c.user_id',input('id') ?: Session::get('user_id'))->select();
		//halt($reys);
		$this->assign('u',$u);
		$this->assign('arts',$arts);
		$this->assign('reys',$reys);
        return view();
    }
	
	
    public function layout()
    {
		
        return view();
    }
	
    //用户登陆
	public function login()
	{
		$this->isLogged();
        //Request::post();接收表单数据
        //接收表单数据
        if(request()->isAjax()) {
            $data = [
                'name' => input('post.name'),
                'password' => input('post.password'),
                'captcha' => input('captcha')
            ];
			if($data['name'] == ''){
				return $this->error('用户不能为空');
			}
			//判断输入在要邮箱还要用户名
		   if (preg_match("/[\w]+(\.[\w]+)*@[\w]+(\.[\w])+/", $data['name'])){ 
               $data['email'] = $data['name'];
			   unset($data['name']);
		   } else {
			   $data['name'] = $data['name'];
		   }
			
            //去模型login检验数据
            $result = model('User')->login($data);
            //$user = User::get(1);
            //$result = $user->login($data);
            if ($result == 1) {
                $this->success('登陆成功', 'index/index/index');
            } else {
                $this->error($result);
            }
        }
        return view(); //加载登陆模板
	}

    //注册
    public function reg()
    {
        //接收表单数据
        if(request()->isAjax()){
        $data = [
            'name'=>input('name'),
            'email'=>input('email'),
            'password'=>input('password'),
            'repassword'=>input('repassword'),
            'captcha'=>input('captcha'),
        ];
        //去模型中验证
           $result = model('User')->reg($data);
           if ($result == 1) {
               $this -> success('注册成功，请登陆','index/user/login');
           }else {
               $this->error($result);
           }
        }
        //加载注册模板
        return $this -> view -> fetch();
    }
	
	
	public function forget()
	{
		return $this->view->fetch();
	}
	
	//忘记密码，mail发送验证码
	public function postmail(Request $request)
    {

		$data = $request->post(); //接收mail表单数据
		$validate = new \app\common\validate\User(); //调用验证器
		$result = $validate->scene('forget')->check($data); //进行数据验证
		if($result) {
		//$user = new \app\common\model\User($data);
        //$user = User::where('email',$data['email'])->find();
		$user = Db::name('user')->where('email',$data['email'])->find();
		if($user) {		
			$code = mt_rand('1111','9999');
			Cache::set('code',$code,600);
			Cache::set('userid',$user['id'],600);
			$result = mailto($data['email'],'重置密码','您的验证码是:'.$code);
				if($result){
					Cache::set('repass',1,60);	//设置repass标志为1存入Cache
					$this->success('验证码已发送成功，请去邮箱查看！');
				} else {
					$this->error('验证码发送失败!');
				}
			}else{
				$this->error('邮箱错误或不存在');
			} 
		} else {
			$this->error($validate->getError(),'index/user/forget');
		}
	}
	
	//接收验证码
	public function postcode()
	{
        $this->isMailed();
        if(request()->isPost()){
		$codedata = input('post.code');
		    if(Cache::get('code')==$codedata) { //无任何输入情况下需排除code为0和Cache为0的情况
			Cache::rm('repass');
			Cache('repass',2,60);
			$this->success('验证成功,请修改密码');
		    } else {
			$this->error('验证错误或已过期！','index/user/forget');
		    }
        }
	}
	
	//忘记密码，找回重置
	public function repass(Request $request)
	{
        $this->isMailed();
		$data = $request->post();
		$validate = new \app\common\validate\User(); //调用验证器
		$result = $validate->scene('repass')->check($data); //进行数据验证
		if(!$result) {  //验证失败
			$validate->getError();
		} else {//验证成功
			$user = Db::name('user')->where('id',Cache::get('userid'))->find();
			if($user){
				$result = Db::name('user')->where('id',Cache::get('userid'))->update(['password' => md5($data['password'])]);
			    if($result){
                    Cache::clear(); //清空缓存
				    $this->success('密码修改成功，请登录','index/user/login');
			        }else{
				    $this->error('密码修改失败,请重新设置！');
			        }
			}else {
				$this->error('用户无效');
			}
		}
	}
	
	//邮箱激活
	public function activate()
	{
		$this->isLogin();
		$user['user_id'] = session::get('user_id');
		$user = UserModel::find($user['user_id']);
		$this->assign('user',$user);
		return view();
	}
	
	//用户修改密码
	public function setpass(request $request)
	{
		$this->isLogin();
		if(request()->isAjax()){
			$data = $request->post();
			$validate = new \app\common\validate\User();
			$res = $validate->scene('setPass')->check($data);
			if(!$res){
				return $this->error($validate->getError());
			}
		//$user = new \app\common\model\User();
		//$result = $user->setpass($data);
		$result = model('User')->setpass($data);
			if($result == 1) {
				Session::clear();
				return $this->success('密码修改成功 请登录', 'index/user/login');
			} else {
				return $this->error($result);
			}
		}
	}
	
	//用户退出
	public function logout()
	{
		//Session::delete('user_id');
		//Session::delete('user_name');
		cookie(null);
		Session::clear();
		
		return json(array('code' => 200, 'msg' => '退出成功'));
		//$this->success('退出成功','index/index');
	}

}